package cn.wlinker.video.monitor.utils;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.wlinker.video.monitor.domain.VideoBaseEntity;
import cn.wlinker.video.monitor.domain.VideoPlayCacheEntity;
import cn.wlinker.video.monitor.domain.dto.PlayUrlDTO;
import cn.wlinker.video.monitor.domain.vo.VideoVO;
import org.apache.commons.lang3.ObjectUtils;

/**
 * 视频流缓存工具类
 *
 * @author gxsjx
 * @version 1.0
 * @date 2022/11/7
 */
public class VideoStreamCacheUtils {

    //创建缓存，过期时间跟随配置文件
    private static final TimedCache<String, VideoPlayCacheEntity> videoStreamCache;

    static {
        videoStreamCache = CacheUtil.newTimedCache(VideoConfigUtils.getVideoConfig().getExpireTime() * 1000);
    }

    public static VideoVO get(PlayUrlDTO playUrlDTO) {
        String id = playUrlDTO.getId();
        VideoPlayCacheEntity videoPlayCacheEntity = videoStreamCache.get(id, false);
        if(ObjectUtils.isEmpty(videoPlayCacheEntity)){
            return null;
        }
        String newPlayUrlDTO = playUrlDTO.toString();
        String oldPlayUrlDTO = videoPlayCacheEntity.getPlayUrlDTO().toString();
        if (!newPlayUrlDTO.equalsIgnoreCase(oldPlayUrlDTO)) {
            return null;
        }
        VideoVO videoVO = videoPlayCacheEntity.getVideoVO();
        VideoBaseEntity videoBaseEntity = MonitorDeviceCacheUtils.get(id);
        if (ObjectUtil.isNotNull(videoVO) && ObjectUtil.isNotEmpty(videoBaseEntity)) {
            videoVO.setName(videoBaseEntity.getName());
        }
        return videoVO;
    }

    public static void put(VideoVO videoVO, PlayUrlDTO playUrlDTO) {
        VideoPlayCacheEntity videoPlayCacheEntity = new VideoPlayCacheEntity(playUrlDTO, videoVO);
        if (ObjectUtil.isEmpty(videoVO.getExpireTime())) {
            videoStreamCache.put(videoVO.getId(), videoPlayCacheEntity);
        } else {
            long betweenMs = DateUtil.betweenMs(videoVO.getExpireTime(), DateUtil.date());
            videoStreamCache.put(videoVO.getId(), videoPlayCacheEntity, betweenMs);
        }
    }


}
